package com.demo.supplier.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.supplier.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT工具类
 * 
 * @author demo
 */
@Slf4j
@Component
public class JwtUtil {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 生成JWT token
     */
    public String generateToken(Long userId, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSecret());
            return JWT.create()
                    .withSubject(userId.toString())
                    .withClaim("username", username)
                    .withIssuedAt(new Date())
                    .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpire() * 1000))
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("生成JWT token失败", e);
            return null;
        }
    }

    /**
     * 验证JWT token
     */
    public boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSecret());
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            log.error("验证JWT token失败", e);
            return false;
        }
    }

    /**
     * 获取用户ID
     */
    public Long getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return Long.valueOf(jwt.getSubject());
        } catch (JWTDecodeException e) {
            log.error("获取用户ID失败", e);
            return null;
        }
    }

    /**
     * 获取用户名
     */
    public String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            log.error("获取用户名失败", e);
            return null;
        }
    }

    /**
     * 获取token过期时间
     */
    public Date getExpiresAt(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        } catch (JWTDecodeException e) {
            log.error("获取token过期时间失败", e);
            return null;
        }
    }

    /**
     * 判断token是否过期
     */
    public boolean isTokenExpired(String token) {
        Date expiresAt = getExpiresAt(token);
        if (expiresAt == null) {
            return true;
        }
        return expiresAt.before(new Date());
    }
}